package com.gxuwz.bignews.fragments;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.gxuwz.bignews.R;
import com.gxuwz.bignews.fragments.FollowsFragment;
import com.gxuwz.bignews.fragments.ProfileFragment;
import com.gxuwz.bignews.fragments.ResetPasswordFragment;
import android.app.AlertDialog;
import android.widget.ImageView;
import com.gxuwz.bignews.model.db.UserDao;

public class UserCenterFragment extends Fragment {

    private TextView tvUsername;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.user_center, container, false);

        // 设置用户信息（实际应用中应该从登录信息获取）
        tvUsername = view.findViewById(R.id.tv_username);
        TextView tvUserId = view.findViewById(R.id.tv_user_id);
        ShapeableImageView ivAvatar = view.findViewById(R.id.iv_avatar);

        // 从 SharedPreferences 读取当前登录用户信息
        SharedPreferences userSp = requireContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        String username = userSp.getString("username", "未登录");
        String phone = userSp.getString("phone", "");
        tvUsername.setText(username);
        // 处理手机号脱敏显示
        String maskedPhone = phone;
        if (phone != null && phone.length() >= 11) {
            maskedPhone = phone.substring(0, 3) + "******" + phone.substring(9);
        }
        tvUserId.setText("ID: " + maskedPhone);

        // 头像资源与标识映射
        final String[] avatarNames = {"dog", "cat", "man", "female", "chicken"};
        final int[] avatarResIds = {R.drawable.ic_avatar_dog, R.drawable.ic_avatar_cat, R.drawable.ic_avatar_male, R.drawable.ic_avatar_female, R.drawable.ic_avatar_chicken};

        // 读取当前头像
        String avatar = userSp.getString("avatar", "cat");
        int avatarIndex = 1; // 默认cat
        for (int i = 0; i < avatarNames.length; i++) {
            if (avatarNames[i].equals(avatar)) {
                avatarIndex = i;
                break;
            }
        }
        ivAvatar.setImageResource(avatarResIds[avatarIndex]);

        // 点击头像弹出选择框
        ivAvatar.setOnClickListener(v -> {
            // 每次点击都重新获取当前头像
            String currentAvatar = userSp.getString("avatar", "cat");
            int currentIndex = 1; // 默认cat
            for (int i = 0; i < avatarNames.length; i++) {
                if (avatarNames[i].equals(currentAvatar)) {
                    currentIndex = i;
                    break;
                }
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("选择头像");
            builder.setSingleChoiceItems(new String[]{"狗狗", "猫咪", "男生", "女生", "小鸡"}, currentIndex, (dialog, which) -> {
                // 更新UI
                ivAvatar.setImageResource(avatarResIds[which]);
                // 更新数据库
                String phoneKey = userSp.getString("phone", "");
                new UserDao(requireContext()).updateAvatar(phoneKey, avatarNames[which]);
                // 更新本地缓存
                SharedPreferences.Editor editor = userSp.edit();
                editor.putString("avatar", avatarNames[which]);
                editor.apply();
                dialog.dismiss();
            });
            builder.setNegativeButton("取消", null);
            builder.show();
        });

        // 设置功能项点击事件
        View profileSetting = view.findViewById(R.id.profile_setting);
        View myFollows = view.findViewById(R.id.my_follows);
        View browseHistory = view.findViewById(R.id.browse_history);
        View resetPassword = view.findViewById(R.id.reset_password);
        MaterialButton btnLogout = view.findViewById(R.id.btn_logout);

        profileSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到个人资料设置Activity
                android.content.Intent intent = new android.content.Intent(getActivity(), com.gxuwz.bignews.view.activity.UserSettingActivity.class);
                startActivity(intent);
            }
        });

        myFollows.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getParentFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_container, new FollowsFragment())
                        .addToBackStack(null)
                        .commit();
            }
        });

        browseHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getParentFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_container, new HistoryFragment())
                        .addToBackStack(null)
                        .commit();
            }
        });

        resetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getParentFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_container, new ResetPasswordFragment())
                        .addToBackStack(null)
                        .commit();
            }
        });

        btnLogout.setOnClickListener(v -> {
            // 清除登录信息
            SharedPreferences sp = requireContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.clear();
            editor.apply();
            Toast.makeText(getContext(), "退出登录", Toast.LENGTH_SHORT).show();
            // 隐藏底部导航栏
            if (getActivity() instanceof com.gxuwz.bignews.MainActivity) {
                ((com.gxuwz.bignews.MainActivity) getActivity()).findViewById(R.id.nav_view).setVisibility(android.view.View.GONE);
            }
            // 跳转到登录页面
            if (getActivity() != null) {
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_container, new LoginFragment())
                        .commit();
            }
        });

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 每次页面返回时刷新用户名
        if (tvUsername != null) {
            SharedPreferences userSp = requireContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
            String username = userSp.getString("username", "未登录");
            tvUsername.setText(username);
        }
    }
}